﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
using SharedLIbrary;

namespace RealTimeMessageInspector
{
    public class WorkerRole : RoleEntryPoint
    {
        // The name of your queue
        const string TopicName = "TemperatureDataLog";
        const string SubscriptionName3 = "LiveMonitorSubscription";
        //threshold in seconds
        const int threshold = 60;

        // QueueClient is thread-safe. Recommended that you cache 
        // rather than recreating it on every request
        SubscriptionClient Client;
        bool IsStopped;
        PingableSensorList sensorlist=new PingableSensorList();
        public override void Run()
        {

            while (true)
            {
                Debug.WriteLine("Working1");
                sensorlist.setPingSensor(10, "10.0.0.7");
                sensorlist.setPingSensor(11, "10.0.0.8");
                sensorlist.setPingSensor(12, "10.0.0.9");
                foreach (var item in sensorlist.getAllFailedSensors())
                {
                    Debug.WriteLine(item.ip);
                }
                Debug.WriteLine("Working2");
            }
            //while (!IsStopped)
            //{
            //    try
            //    {
            //        // Receive the message
            //        BrokeredMessage receivedMessage = null;
            //        receivedMessage = Client.Receive();

            //        if (receivedMessage != null)
            //        {
                        
            //            // Process the message
            //            Trace.WriteLine("Processing", receivedMessage.SequenceNumber.ToString());

            //            //storing the last accessed time in the sensor table 


            //            receivedMessage.Complete();
            //        }

            //        Debug.WriteLine("Working1");
            //        //sensorlist.setPingSensor(10, "10.0.0.7");
            //        //sensorlist.setPingSensor(11, "10.0.0.8");
            //        //sensorlist.setPingSensor(12, "10.0.0.9");
            //        //foreach (var item in sensorlist.getAllFailedSensors())
            //        //{
            //        //    Debug.WriteLine(item.ip);
            //        //}
            //Debug.WriteLine("Working2");
            //        //retrieving the list of sensors with its last accessed time

            //        //comparing the time with the current utc time

            //        //if difference is more than threshold, set the status of sensor to offline

            //        //get the device id of the sensor 
                    
            //        //get the ip address of the device

            //        //add the sensor id and device ip address to a pingable sensors list, if it already does not exist
            //    }
            //    catch (MessagingException e)
            //    {
            //        if (!e.IsTransient)
            //        {
            //            Trace.WriteLine(e.Message);
            //            //throw;
            //        }

            //        Thread.Sleep(1000);
            //    }
            //    catch (OperationCanceledException e)
            //    {
            //        if (!IsStopped)
            //        {
            //            Trace.WriteLine(e.Message);
            //           // throw;
            //        }
            //    }
            //}
        }

        public override bool OnStart()
        {

            // Set the maximum number of concurrent connections 
            ServicePointManager.DefaultConnectionLimit = 12;

            // Create the queue if it does not exist already
            string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
            var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
            try
            {
                //Create the Topic
                if (!namespaceManager.TopicExists(TopicName))
                {
                    namespaceManager.DeleteTopic(TopicName);
                }
                //Create subscriptions for the topic
                if (!namespaceManager.SubscriptionExists(TopicName, SubscriptionName3))
                {
                    namespaceManager.CreateSubscription(TopicName, SubscriptionName3);
                }
            }
            catch (MessagingException e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
            // Initialize the connection to Service Bus Queue

            // Creates the subscription client
            Client = SubscriptionClient.CreateFromConnectionString(connectionString, TopicName, SubscriptionName3);
            IsStopped = false;
            return base.OnStart();
        }

        public override void OnStop()
        {
            // Close the connection to Service Bus Queue
            IsStopped = true;
            Client.Close();
            base.OnStop();
        }
    }
}
